package controllers.interceptors

import base.DuoyuConfig
import com.jfinal.core.Controller
import com.jfinal.validate.Validator
import base.Message
import base.State
import controllers.UserController

class VerifyCodeValidator: Validator() {

    override fun validate(c: Controller) {
        if (DuoyuConfig.DEV_MODE){
            return
        }
        val serverVerifyCode = c.getSessionAttr<String>(UserController.PARA_VERIFY_CODE)
        c.removeSessionAttr(UserController.PARA_VERIFY_CODE)

        if (serverVerifyCode == null || serverVerifyCode.isEmpty()){
            addError(UserController.PARA_VERIFY_CODE, State.ERROR_USER_VERIFY_CODE_EXPIRED)
            return
        }
        val time = System.currentTimeMillis()
        val (code, generateTime) = serverVerifyCode.split("#")
        if (isExpired(time, generateTime.toLong())){
            addError(UserController.PARA_VERIFY_CODE, State.ERROR_USER_VERIFY_CODE_EXPIRED)
            return
        }
        val clientVerifyCode = c.get(UserController.PARA_VERIFY_CODE)
        if (code != clientVerifyCode){
            addError(UserController.PARA_VERIFY_CODE, State.ERROR_USER_VERIFY_CODE)
        }
    }

    override fun handleError(c: Controller) {
        val error = c.getAttr<String>(UserController.PARA_VERIFY_CODE)
        val msg = Message(State.STATE_FAIL, data = State.getEorrorStr(error))
        c.renderJson(msg)
    }

    private fun isExpired(time: Long, since: Long): Boolean{
        return (time-since)/1000/60 > 10
    }
}